#include <jni.h>
#include <string>
#include "include/marisa.h"
static marisa::Trie trie;
static marisa::Agent agent;

extern "C" JNIEXPORT void JNICALL
Java_org_balilar_app_myimeClent_load(
        JNIEnv* env,
        jobject ,/* this */
        jstring filename) {

    const char* pfilename = env->GetStringUTFChars(filename, 0);
    trie.load(pfilename);

}

extern "C" JNIEXPORT jstring JNICALL
Java_com_example_ctextjni_MainActivity_stringFromJNI(
        JNIEnv* env,
        jobject /* this */) {
    std::string hello = "2211212121";
    return env->NewStringUTF(hello.c_str());
}

extern "C" JNIEXPORT void JNICALL
Java_org_balilar_app_myimeClent_clear(
        JNIEnv* env,
        jobject /* this */) {

    trie.clear();

}

extern "C" JNIEXPORT void JNICALL
Java_org_balilar_app_myimeClent_setQuery(
        JNIEnv* env,
        jobject /* this */,
        jstring searchStr) {

    const char* pSearch = env->GetStringUTFChars(searchStr, 0);
    agent.set_query(pSearch);
    agent.set_key((size_t)0);
    agent.set_search_id(0);
}

extern "C" JNIEXPORT jbyteArray JNICALL
Java_org_balilar_app_myimeClent_search(
        JNIEnv* env,
        jobject /* this */) {

    size_t id = agent.key().id();
    trie.predictive_search(agent);
    if (id == agent.key().id()){
        return NULL;
    }
    if (agent.key().length() > 0){
        char cOut[256];
        int i;
        for (i = 0; i < agent.key().length() && i < 255; i++){
            cOut[i] = agent.key().ptr()[i];
        }
        cOut[i] = 0;
        jbyteArray outByte = env->NewByteArray(agent.key().length());
        env->SetByteArrayRegion(outByte,0, agent.key().length(), reinterpret_cast<jbyte *>(cOut));

        return outByte;
    }
    else{
        return NULL;
    }
}

extern "C" JNIEXPORT jbyteArray JNICALL
Java_org_balilar_app_myimeClent_searchAdd(
        JNIEnv* env,
        jobject /* this */) {

    size_t id = agent.key().id();
    trie.predictive_search_add(agent);
    if (id == agent.key().id()){
        return NULL;
    }
    if (agent.key().length() > 0){
        char cOut[256];
        int i;
        for (i = 0; i < agent.key().length() && i < 255; i++){
            cOut[i] = agent.key().ptr()[i];
        }
        cOut[i] = 0;

        jbyteArray outByte = env->NewByteArray(agent.key().length());
        env->SetByteArrayRegion(outByte,0, agent.key().length(), reinterpret_cast<jbyte *>(cOut));

        return outByte;
    }
    else{
        return NULL;
    }
}
